#! /bin/bash


error_nu=60
day_ip=/tmp/sshd_secure_ip_$(date +%Y%m%d)
day_log=/tmp/sshd_secure_log_$(date +%Y%m%d)

if test -e $day_ip
then
	echo "found "$day_ip
else
	touch $day_ip
fi
if test -e $day_log
then
	echo "found "$day_log
else
	touch $day_log
fi

fail_data=`cat /var/log/secure | awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}'`

# echo $fail_data > $day_log

for i in $fail_data
do
  IP=`echo $i |awk -F= '{print $1}'`
  NUM=`echo $i|awk -F= '{print $2}'`
	
  if test ${NUM} -gt $[error_nu]
  then

    grep $IP /etc/hosts.deny > /dev/null
    if [ $? -gt 0 ];then
      echo "sshd:$IP:deny" >> /etc/hosts.deny
	  firewall-cmd --zone=public --add-rich-rule="rule family='ipv4' source address='$IP' drop" --permanent
	  ret=$?
	   # echo -e "ip: $IP \n try: $NUM \n too many errors \n firewall-cmd exec result: $ret" | mail -s "boat server info" junchao82@qq.com
	  echo "$IP too many errors :"${NUM} " firewall return: "${ret} >> $day_log
    fi
  fi
done

if test ${#faill_data[*]} -gt 0
then
	echo "reload firewall" > $day_log
	firewall-cmd --reload
fi
